package cn.wuxing.mediation.web.controller.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class StringToLongIdGenerator {

    /**
     * 将字符串转为固定的 Long ID
     *
     * @param input 输入字符串
     * @return 唯一的 Long ID
     */
    public static long generateId(String input) {
        try {
            // 使用 SHA-256 获取字符串的哈希值
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));

            // 截取哈希值的前 8 个字节，转化为 long
            long result = 0L;
            for (int i = 0; i < 8; i++) {
                result = (result << 8) | (hashBytes[i] & 0xFF);
            }

            // 返回正数
            return result < 0 ? -result : result;

        } catch (Exception e) {
            throw new RuntimeException("Error generating ID", e);
        }
    }

    public static void main(String[] args) {
        String input = "exampleString";
        System.out.println("Input: " + input);
        System.out.println("Generated ID: " + generateId(input));

        // 再次验证相同字符串生成的 ID 是否一致
        System.out.println("Generated ID (repeat): " + generateId(input));

        // 测试不同字符串
        System.out.println("Different Input: " + generateId("anotherString"));
    }
}